package com.bjpowernode.web.controller;

import com.bjpowernode.constants.enums.Code;
import com.bjpowernode.util.CommonUtils;
import com.bjpowernode.web.resp.ResponseObj;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 麦翔盛
 * @ClassName: SmsController
 * @Package: com.bjpowernode.web.controller
 * @description: 短信接口
 * @date 2022/5/20 21:38
 */
@Api(tags = "短信接口")
@RestController
public class SmsController extends BaseController {

    /**
     * 发送注册验证码
     * @param phone 电话号码
     */
    @ApiOperation(value = "发送注册验证码")
    @GetMapping("/v1/sms/code/reg")
    public ResponseObj sendRegisterSmsCode(@RequestParam( value = "phone") String phone) {
        ResponseObj responseObj = ResponseObj.fail();
        //校验手机号码格式
        if (!CommonUtils.checkPhone(phone)) {
            return ResponseObj.error(Code.PHONE_FORMAT);
        }
        //校验是否已经发送
        if (smsService.checkRegCodeExists(phone)) {
            //如果已经发送 则不再请求
            return ResponseObj.error(Code.SMS_REG_CODE_EXISTS);
        }
        //发送验证码
        try {
            boolean flag = smsService.sendRegisterSmsCode(phone);
            if (flag) {
                //校验是否发送成功
                return ResponseObj.ok();
            }
        } catch (Exception e) {
            return ResponseObj.error(Code.SMS_ERROR);
        }
        return responseObj;
    }

    @ApiOperation(value = "发送用户登录验证码")
    @GetMapping("/v1/sms/code/login")
    public ResponseObj sendUserLoginCode(@RequestParam( value = "phone") String phone){
        ResponseObj result = ResponseObj.fail();
        //校验电话号码格式
        if (!CommonUtils.checkPhone(phone)){
            return ResponseObj.error(Code.PHONE_FORMAT);
        }

        //判断是否已经发送
        if (smsService.checkLogCodeExists(phone)){
            return ResponseObj.error(Code.SMS_LOG_CODE_EXISTS);
        }

        //发送验证码
        try {
            boolean isSend = smsService.sendLoginSmsCode(phone);
            if (isSend){
                return ResponseObj.ok();
            }

        } catch (Exception e) {
            return ResponseObj.error(Code.SMS_ERROR);
        }
        return result;
    }

}
